package com.itheima.jdk;

import com.itheima.dao.UserDao;
import com.itheima.dao.impl.UserDaoImpl;
import com.itheima.dao.impl.UserImpl;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class DemoCglibProxy {


    public static void main(String[] args) {
        UserDao userDao = new UserDaoImpl();

        UserImpl user1 = new UserImpl();
        UserImpl user = (UserImpl) Enhancer.create(user1.getClass(), new MethodInterceptor() {
            /**
             *
             * @param o             代理对象（如果不指定目标对象，则此代理对象为null）
             * @param method        执行的方法对象
             * @param objects       执行方法对象的参数列表
             * @param methodProxy   返回执行的方法对象的返回值，如果执行的方法是void，则此返回值可以为null
             * @return
             * @throws Throwable
             *
             *  com.itheima.dao.impl.UserDaoImpl$$EnhancerByCGLIB$$3cbb4d44.save(<generated>)
             */
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

                Object obj = null;

                try {
                    System.out.println("前置增强");
                    obj = method.invoke(user1, args);
                    System.out.println("后置增强");
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("异常增强");
                } finally {
                    System.out.println("最终增强");
                }
                return obj;
            }
        });
        user.save();
    }

}
